package com.aaron.aaronnews;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.aaron.model.Parameter;
import com.aaron.service.SyncHttp;
import com.aaron.util.UrlUtil;

public class DetailsActivity extends Activity{

	private ViewFlipper mNewsBodyFlipper;
	private LayoutInflater mNewsBodyInflater;
	private TextView newsTitle;
	private TextView newsPtimeAndSource;
	private TextView newsDetails;
	private TextView titleBarTitle;
	
	private Button newsdetailsPrevious;
	private Button newsdetailsNext;
	private Button newsdetailsTitlebarComm;
	
	private LinearLayout newsReplyEditLayout;
	private LinearLayout newsReplyImageLayout;
	private EditText newsReplyContent;
	
	private float mStartX;
	private float mStartY;
	
	private ArrayList<HashMap<String, Object>> newsList;
	private int mPosition = 0;
	private String nid; //新闻ID
	private int mCurrentFirst = 0;
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newsdetails);
		
		newsdetailsPrevious = (Button)findViewById(R.id.newsdetails_titlebar_previous);
		newsdetailsNext = (Button)findViewById(R.id.newsdetails_titlebar_next);
		newsdetailsTitlebarComm = (Button)findViewById(R.id.newsdetails_titlebar_comments);
		NewsDetailsTitleBarOnClickListener newsDetailsTitleBarOnClickListener = new NewsDetailsTitleBarOnClickListener();
		newsdetailsPrevious.setOnClickListener(newsDetailsTitleBarOnClickListener);
		newsdetailsNext.setOnClickListener(newsDetailsTitleBarOnClickListener);
		newsdetailsTitlebarComm.setOnClickListener(newsDetailsTitleBarOnClickListener);
		
		newsReplyEditLayout = (LinearLayout)findViewById(R.id.news_reply_edit_layout);
		newsReplyImageLayout = (LinearLayout)findViewById(R.id.news_reply_img_layout);
		((ImageButton)findViewById(R.id.news_reply_img_btn)).setOnClickListener(newsDetailsTitleBarOnClickListener);
		((Button)findViewById(R.id.news_reply_post)).setOnClickListener(newsDetailsTitleBarOnClickListener);
		newsReplyContent = (EditText)findViewById(R.id.news_reply_edittext);
		
		try{
			//获取传递的信息
			Intent intent = getIntent();
			Bundle bundle = intent.getExtras();
			//设置分类标题栏
			String categoryName = bundle.getString("categoryTitle");
			titleBarTitle = (TextView)findViewById(R.id.newsdetails_titlebar_title);
			titleBarTitle.setText(categoryName);
			//获取position
			mPosition = bundle.getInt("position");
			mCurrentFirst = mPosition;
			Serializable serializable = bundle.getSerializable("newsData");
			newsList = (ArrayList<HashMap<String, Object>>)serializable;
			
			mNewsBodyInflater = getLayoutInflater();
			
			mNewsBodyFlipper = (ViewFlipper)findViewById(R.id.news_body_flipper);
			
			show(0);
		}catch(Exception e){
			Log.e("create", e.getMessage());
		}
	}
	
	private void show(int index){
		try{
			//获取点击新闻基本信息
			HashMap<String, Object> hashMap = newsList.get(mPosition);
			nid = hashMap.get("nid").toString();
			//动态创建新闻视图，并赋值
			View newsBodyView = mNewsBodyInflater.inflate(R.layout.news_body, null);
			
			newsTitle = (TextView)newsBodyView.findViewById(R.id.news_body_title);
			newsPtimeAndSource = (TextView)newsBodyView.findViewById(R.id.news_body_ptime_source);
			newsDetails = (TextView)newsBodyView.findViewById(R.id.news_body_details);
			
			//新闻回复数
			newsdetailsTitlebarComm.setText(hashMap.get("newslist_item_comments")+"跟帖");
			//设置新闻标题
			newsTitle.setText(hashMap.get("newslist_item_title").toString());
			//设置出处和发表时间
			newsPtimeAndSource.setText("来源：" + hashMap.get("newslist_item_from") 
					+ " " + hashMap.get("newslist_item_ptime"));
			//网络获取新闻内容
			String urlParams = "nid=" + nid;
			PageTask task = new PageTask();
			task.execute(UrlUtil.HOST + UrlUtil.GETNEWS, urlParams);
			
			//把新闻视图添加到Flipper中
			
			mNewsBodyFlipper.addView(newsBodyView, index);
			//给新闻Body添加触摸事件
			newsDetails.setOnTouchListener(NewsBodyOnTouchListener);
		}catch(Exception e){
			Log.e("showDetail", e.getMessage());
		}
	}
	
	private class NewsDetailsTitleBarOnClickListener implements OnClickListener{
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		@Override
		public void onClick(View v) {
			switch(v.getId()){
			case R.id.newsdetails_titlebar_previous:
				showPrevious();
				break;
			case R.id.newsdetails_titlebar_next:
				showNext();
				break;
			case R.id.newsdetails_titlebar_comments:
				Intent intent = new Intent(DetailsActivity.this, CommentsActivity.class);
				startActivity(intent);
				break;
			case R.id.news_reply_img_btn:
				//显示输入框Layout，隐藏图片按钮Layout
				newsReplyEditLayout.setVisibility(View.VISIBLE);
				newsReplyImageLayout.setVisibility(View.GONE);
				newsReplyContent.requestFocus();
				//显示键盘
				imm.showSoftInput(newsReplyContent, InputMethodManager.SHOW_FORCED); 
				break;
			case R.id.news_reply_post:
				//使用post，将分线程加载到主线程
				new Thread(runnable).start();
				//隐藏输入框，显示图片按钮
				newsReplyEditLayout.setVisibility(View.GONE);
				newsReplyImageLayout.setVisibility(View.VISIBLE);
				//隐藏键盘
				imm.hideSoftInputFromWindow(newsReplyContent.getWindowToken(), 0); 
				break;
			default:
				break;
			}
			
			
		}
		
	}
	
	private OnTouchListener NewsBodyOnTouchListener = new OnTouchListener() {
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int action = event.getAction();
			System.out.println("-------值为：" + action);
			switch(action){
			//手指按下
			case MotionEvent.ACTION_DOWN:
				//记录起始坐标
				mStartX = event.getX();
				//隐藏输入框，显示图片按钮
				newsReplyEditLayout.setVisibility(View.GONE);
				newsReplyImageLayout.setVisibility(View.VISIBLE);
				//隐藏键盘
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(newsReplyContent.getWindowToken(), 0);
				break;
			case MotionEvent.ACTION_UP:
				//往左滑动
				if(event.getX() < mStartX-50){
					showNext();
				}
				//往右滑动
				else if(event.getX() > mStartX+50){
					showPrevious();
				}
				break;
			case MotionEvent.ACTION_CANCEL:
				//往左滑动
				if(event.getX() < mStartX-50){
					showNext();
				}
				//往右滑动
				else if(event.getX() > mStartX+50){
					showPrevious();
				}
				break;
			default:
				break;
			}
			
			return true;
		}
	};
	
	private void showPrevious(){
		mPosition--;
		if(mPosition >= 0){
			//设置上一屏动画
			mNewsBodyFlipper.setInAnimation(this, R.anim.push_right_in);// 定义下一页进来时的动画
			mNewsBodyFlipper.setOutAnimation(this, R.anim.push_right_out);// 定义当前页出去的动画
			if(mCurrentFirst > 0){
				show(0);
				mCurrentFirst--;
				//mNewsBodyFlipper.showNext();
			}
			mNewsBodyFlipper.showPrevious();
		}else{
			mPosition++;
			Toast.makeText(this, "已经是第一篇新闻", Toast.LENGTH_SHORT).show();
		}
	}
	
	private void showNext(){
		mPosition++;
		if(mPosition < newsList.size()){
			//设置下一屏动画
			mNewsBodyFlipper.setInAnimation(this, R.anim.push_left_in);
			mNewsBodyFlipper.setOutAnimation(this, R.anim.push_left_out);
			if(mPosition >= mNewsBodyFlipper.getChildCount()){
				show(mNewsBodyFlipper.getChildCount());
			}
			mNewsBodyFlipper.showNext();
		}else{
			Toast.makeText(this, "没有下一条新闻了", Toast.LENGTH_LONG).show();
			mPosition--;
		}
	}
	
	class PageTask extends AsyncTask<String, Integer, String>{
		
		@Override
		protected String doInBackground(String... params) {
			String res = "网络连接失败，请稍后再试";
			if(params.length==2){
				String urlStr = params[0];
				String urlParams = params[1];
				SyncHttp http = new SyncHttp();
				try {
					Log.w("http", "获取网络");
					String returnJson = http.httpGet(urlStr, urlParams);
					JSONObject jsonObj = new JSONObject(returnJson);
					int retCode = jsonObj.getInt("ret");
					if(0 == retCode){
						JSONObject dataObject = jsonObj.getJSONObject("data");
						JSONObject newsObject = dataObject.getJSONObject("news");
						res = newsObject.getString("body");
					}
				} catch (Exception e) {
					Log.e("doInBackground", e.getMessage());
				}
			}
			return res;
		}
	

		@Override  
		protected void onPostExecute(String result) {  
			try{
				newsDetails.setText(Html.fromHtml(result));
			}catch(Exception e){
				Log.e("onPostExecute", e.getMessage());
			}
		}  


	}
	
	/**
	 * 发表评论,采用另外一种异步获取网络的方式
	 * @author Administrator
	 *
	 */
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle data = msg.getData();
			String returnValue = data.getString("value");
			if("success".equals(returnValue)){
				Toast.makeText(DetailsActivity.this, R.string.post_success, Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(DetailsActivity.this, R.string.post_failure, Toast.LENGTH_SHORT).show();
			}
			
		}
	};
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			String returnValue="error";
			SyncHttp syncHttp = new SyncHttp();
			String url = UrlUtil.HOST + UrlUtil.REPLYCOMMENT;
			List<Parameter> params = new ArrayList<Parameter>();
			params.add(new Parameter("nid", nid + ""));
			params.add(new Parameter("region", "江苏省连云港市"));
			params.add(new Parameter("content", newsReplyContent.getText().toString()));
			try {
				String retStr = syncHttp.httpPost(url, params);
				JSONObject jsonObject = new JSONObject(retStr);
				int retCode = jsonObject.getInt("ret");
				if (0 == retCode){
					returnValue = "success";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			Message msg = new Message();  
	        Bundle data = new Bundle();  
	        data.putString("value",returnValue);  
	        msg.setData(data);  
	        handler.sendMessage(msg);  
		}
	};
}
